﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Net;
using Microsoft.Office.Interop.PowerPoint;
using Microsoft.Office.Core;
using System.Windows.Forms;
using System.Windows.Threading;

namespace TakeNote
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        
        Server m_ServerClass = new Server();
        int tray = 0;
        string tread;
        int retray = 0;
        StreamWriter sw;
        private string m_sIPAddress;
        private int m_nPort;
        
        string sDirPath;
        string sDirectoryPath;

        NotifyIcon ni = new NotifyIcon();
        public Presentation ppt1, ppt;
        public double Window1_width = 0;
       

        public MainWindow()
        {
        
            InitializeComponent();
            StreamReader tsr = File.OpenText(Environment.CurrentDirectory + "\\\\" + "trayMode.txt");
            tread = tsr.ReadLine();
            
            //트레이
            if (tread.Equals("1"))
            {
                tray = 1;
                ni.Icon = new System.Drawing.Icon("icon.ico");
                ni.Visible = true;
                ni.DoubleClick +=
                    delegate(object sender, EventArgs args)
                    {
                        this.Show();
                        this.WindowState = WindowState.Normal;
                    };
            }
            System.Drawing.Point pt = System.Windows.Forms.Control.MousePosition;
            textBox4.Text = "X 좌표 : " + pt.X.ToString() + " Y 좌표 : " + pt.Y.ToString();
            this.Topmost = false; //MainWindow
        }
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


         //   this.FileOpenButtonIsEnabled(false);  // ppt 열기 false  나중에 넣을것!
            buttonServerStop.IsEnabled = false;    //serverstop enable
            try
            {
                                m_ServerClass.WindowMain = this;
                

                string sHostName = "";
                sHostName = Dns.GetHostName();
                IPHostEntry ipHostEntry = Dns.GetHostByName(sHostName);
                IPAddress[] ipAddress = ipHostEntry.AddressList;    //  주소가져오기 현재것들을 가져오는거

                m_sIPAddress = ipAddress[0].ToString();     //주소가져오기
                m_nPort = 7800;

                m_ServerClass.ServerIP = m_sIPAddress;
                m_ServerClass.ServerPort = m_nPort;

                textBox2.Text = m_sIPAddress;              
                textBox3.Text = m_nPort.ToString();                

                //image폴더 생성하기
                sDirPath = Environment.CurrentDirectory + "\\images";
                DirectoryInfo directory = new DirectoryInfo(sDirPath);

                if (directory.Exists == false)
                {
                    directory.Create();
                }
                // wsacancelblockingcall을 호출하여 차단 작업이 중단
                            
                //this.showin
            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }                 
        }

        protected override void OnStateChanged(EventArgs e)
        {
            //트레이 상황
            if (tray == 1 && WindowState == WindowState.Minimized)
            {
                this.Hide();
            }

            //트레이 안된상황
            if (tray == 0 && WindowState == WindowState.Minimized)
            {
                ni.Visible = false;
            }

            //폼 로드(트레이 안된상태) 후 트레이 재설정
            if (retray == 1 && WindowState == WindowState.Minimized)
            {
                ni.Icon = new System.Drawing.Icon("icon.ico");
                ni.Visible = true;
                ni.DoubleClick +=
                    delegate(object sender, EventArgs args)
                    {
                        this.Show();
                        this.WindowState = WindowState.Normal;
                    };
                retray = 0;
            }
            base.OnStateChanged(e);
        }



        private void button1_Click(object sender, RoutedEventArgs e)     //폴더안에 삭제
        {
            
        }

        private void chx_TrayCancel_Checked(object sender, RoutedEventArgs e)
        {
            if (chx_TrayCancel.IsChecked == true)
            {
                chx_TrayOk.IsChecked = false;
            }

        }

        private void chx_TrayOk_Checked(object sender, RoutedEventArgs e)
        {
            if (chx_TrayOk.IsChecked == true)
            {
                chx_TrayCancel.IsChecked = false;
            }
        }

        private void btn_Tray_Click_1(object sender, RoutedEventArgs e)
        {
            sw = new StreamWriter(Environment.CurrentDirectory + "\\\\" + "trayMode.txt");
             
            if (chx_TrayOk.IsChecked == true)
            {
                tray = 1;
                retray = 1;
                sw.WriteLine("1");
                sw.Close();
            }

            if (chx_TrayCancel.IsChecked == true)
            {
                tray = 0;
                sw.WriteLine("0");
                sw.Close();
            }

            if (chx_TrayOk.IsChecked == false && chx_TrayCancel.IsChecked == false)
            {
                System.Windows.Forms.MessageBox.Show("트레이를 설정하세요", "트레이 선택", System.Windows.Forms.MessageBoxButtons.OK, MessageBoxIcon.Information);
                sw.Close();
            }

            chx_TrayOk.IsChecked = false;
            chx_TrayCancel.IsChecked = false;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                ni.Visible = false;
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }   

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ////1. Image 저장 2.파일 전송 3. PPT Open 4. ppt열기 5. 파일 삭제  

            Microsoft.Win32.OpenFileDialog open = new Microsoft.Win32.OpenFileDialog();
            open.Title = "    PowerPoint 선택하세요";
            open.Multiselect = false;
            open.Filter = "Images (*.PPTX)|*.PPTX|" + "All files (*.*)|*.*"; //
            sDirectoryPath = sDirPath + "\\images";
                        
            int i = 0;

            if (((bool)open.ShowDialog()))
            {
                Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                ppt1 = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);

                for (i = 0; i < ppt1.Slides.Count; ++i)
                {
                    ppt1.Slides[i + 1].Export(sDirectoryPath + i + ".jpg", "jpg", (int)ppt1.Slides[i + 1].Master.Width, (int)ppt1.Slides[i + 1].Master.Height);
                }
                ppt1.Close();  //이미지 저장하기  
                
                //////////////////////파일전송/////////////////////////////
                // string[] files = System.IO.Directory.GetFiles(sDirPath);
                // foreach (string FileName in files)
                // {
                //    System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileName);
                //    long nFileSize = fileInfo.Length;
                //    m_ServerClass.FileName.Add(FileName);
                //    m_ServerClass.FileSize.Add((int)nFileSize);
                // }
                // m_ServerClass.DoRunning();  //파일 전송
                                             
                ppt = app.Presentations.Open(open.FileName, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoTrue);
                
                //  1. ppt열기
                ppt.SlideShowSettings.Run();                 //슬라이드 활성화.
                System.Threading.Thread.Sleep(1000);

                this.Topmost = false; //MainWindow  
                this.WindowState = WindowState.Minimized;  //최소화시키기
                

                // 2. 투명창 win1 열기
                Window1 win1 = new Window1();
                win1.Topmost = true;
                win1.Show();
                                
                System.Threading.Thread.Sleep(1000);
                ppt.SlideShowWindow.View.Next();
                   
    
                //////////////////////////파일삭제////////////////////////////
                // DirectoryInfo Dir_del = new DirectoryInfo(sDirPath);
                // FileInfo[] files1 = Dir_del.GetFiles();
                // foreach (FileInfo fi in files1)
                //{
                //    fi.Delete();     
                //}
                // ppt.SlideShowWindow.View.GotoSlide(12, MsoTriState.msoTrue); //12 슬라이드로 가기
                // System.Threading.Thread.Sleep(1000);
                // win1.BeginInit();  //처음에서 시작하기
                // win1.Activate();   //활성화
            }
        }       
   
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog().Equals(System.Windows.Forms.DialogResult.Cancel))            //예외처리  할것
                {
                    return;
                }
                string selected = dialog.SelectedPath;
                string[] files = System.IO.Directory.GetFiles(selected);

                foreach (string FileName in files)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(FileName);
                    long nFileSize = fileInfo.Length;
                    m_ServerClass.FileName.Add(FileName);
                    m_ServerClass.FileSize.Add((int)nFileSize);
                }
                m_ServerClass.DoRunning();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void buttonServerStart_Click(object sender, RoutedEventArgs e) //서버시작
        {

            try
            {
                m_ServerClass.StartSocket();              
                textBox3.Text = "서버 스타트 ";
                buttonServerStart.IsEnabled = false;
                buttonServerStop.IsEnabled = true;
        
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }        
        }

        public void SetText(string sString)  
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                   textBox5.Text= sString ;
                  
                }));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
           
        }

        private void buttonServerStop_Click(object sender, RoutedEventArgs e) //서버정지
        {
            try
            {

                m_ServerClass.StopSocket();
                buttonServerStart.IsEnabled = true;
                buttonServerStop.IsEnabled = false;
             
             
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                m_ServerClass.CloseSocket();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
       {      
            Window1 win1 = new Window1();
            win1.Topmost = true;
            win1.Show();
        }

        public void FileOpenButtonIsEnabled(bool qBool)
        {
            try
            {
                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                {
                    button2.IsEnabled = qBool;
                }));
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
    }
}



